import json

from django_redis import get_redis_connection

from apps.goods.models import SKU
from utils.superjiajiemi import jiajiemiSuper


def easy_shopping(request):
    # '''----------------------简单的购物车----------------------'''

    # 判断用户是否登陆 1.登陆redis, 2.未登录cookie  获得sku即可
    shoppingcart = []
    amount = 0
    if request.user.is_authenticated:
        client = get_redis_connection('carts')
        skusid_byte_list = client.hkeys(request.user.id)

        for sku_id_byte in skusid_byte_list:
            if sku_id_byte.decode() != 'None':
                amount += 1
                shoppingcart_sku_id = sku_id_byte.decode()
                values_byte_dict = client.hget(request.user.id, shoppingcart_sku_id)

                shoppingcart_sku = SKU.objects.get(id=shoppingcart_sku_id)

                shoppingcart.append({
                    'name': shoppingcart_sku.name,
                    'count': json.loads(values_byte_dict.decode()).get('count'),
                    'image': shoppingcart_sku.default_image.url
                })
        return shoppingcart,amount

    else:

        # 格式 {sku_id:{'':''}}  需要sku,数量,总数
        data = request.COOKIES.get('carts')  # 二进制
        if data:
            cookie_dict = json.loads(jiajiemiSuper.jiemi(data))

            for sku_id, values_dict in cookie_dict.items():
                if sku_id != 'None':
                    amount += 1
                    shoppingcart_sku = SKU.objects.get(id=sku_id)

                    shoppingcart.append({
                        'name': shoppingcart_sku.name,
                        'count': values_dict.get('count'),
                        'image': shoppingcart_sku.default_image.url
                    })
        return shoppingcart, amount